<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>电子签名</title>
  <style>
    canvas {
      border: 1px solid #333;
    }
  </style>
</head>

<body>
  <canvas width="300" height="200"></canvas>
  <p>
    <button>清空</button>
    <button>保存</button>
  </p>
</body>
<script>
  let canvas = document.querySelector("canvas")
  let ctx = canvas.getContext("2d")

  let lastX = 0, lastY = 0;
  let tag=false;
  canvas.addEventListener("mousedown", (e) => {
    lastX = e.offsetX;
    lastY = e.offsetY
    tag=true;
    
  })

  canvas.addEventListener("mousemove", (e) => {
    if(!tag)return;
    ctx.beginPath()
    ctx.moveTo(lastX,lastY)
    ctx.lineTo(e.offsetX,e.offsetY)
    lastX=e.offsetX
    lastY=e.offsetY
    ctx.stroke()
  })

  canvas.addEventListener("mouseup", (e) => {
    tag=false

  })
</script>

</html>